package com.seckill.service.impl;

import com.seckill.activemq.ActivemqSender;
import com.seckill.dao.MiaoshaOrderDao;
import com.seckill.dao.OrderInfoDao;
import com.seckill.domain.MiaoshaUser;
import com.seckill.domain.OrderInfo;
import com.seckill.redis.RedisService;
import com.seckill.service.GoodsService;
import com.seckill.service.MiaoshaOrderService;
import com.seckill.service.MiaoshaService;
import com.seckill.service.OrderService;
import com.seckill.vo.GoodsVo;
import com.seckill.vo.OrderStatusEnum;
import java.util.Date;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yangjunwei
 * @date 2021/11/2 10:46 上午
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    MiaoshaOrderDao miaoshaOrderDao;

    @Autowired
    OrderInfoDao orderInfoDao;

    @Autowired
    RedisService redisService;

    @Autowired
    ActivemqSender mqSender;

    @Autowired
    GoodsService goodsService;

    @Autowired
    MiaoshaOrderService miaoshaOrderService;

    @Autowired
    MiaoshaService miaoshaService;

    @Override
    public OrderInfo createOrder(GoodsVo goodsVo, MiaoshaUser miaoshaUser) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(miaoshaUser.getId());
        orderInfo.setGoodsId(goodsVo.getId());
        orderInfo.setGoodsName(goodsVo.getGoodsName());
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsPrice(goodsVo.getMiaoshaPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setCreateDate(new Date());
        long insert = orderInfoDao.insertOrderInfo(orderInfo);
        if (insert <= 0) {
            //订单创建失败
            return null;
        }
        return orderInfo;
    }

    @Override
    public OrderInfo getOrderById(Integer orderId) {
        return orderInfoDao.getOrderById(orderId);
    }

    /**
     * 订单过期取消
     */
    @Override
    public void orderDelayCancel(Integer orderId) {
        OrderInfo orderInfo = this.getOrderById(orderId);
        //未支付取消订单
        if (Objects.equals(orderInfo.getStatus(), OrderStatusEnum.UNPAID.getStatusCode())) {
            //update订单状态
            orderInfoDao.updateOrderStatusByOrderId(orderId, OrderStatusEnum.EXPIRED.getStatusCode());
            //库存回退
            incrGoods(orderInfo.getGoodsId(), orderInfo.getUserId());
        }
    }

    /**
     * 商品库存回退 数据库->redis缓存->本地内存
     *
     * @param goodsId 商品Id
     * @param userId  用户Id
     */
    private void incrGoods(long goodsId, long userId) {
        //数据库
        goodsService.incrStock(goodsId);
        //删除DB中的秒杀信息

        //删除缓存中的用户订单信息
        miaoshaOrderService.deleteUserGoodsCache(goodsId, userId);
        //redis和本地内存
        miaoshaService.incrStock(goodsId);
    }


}
